package middleware

import (
	"fmt"
	"log"
	"net/http"
	"runtime/debug"

	"github.com/gin-gonic/gin"
)

func Recovery() gin.HandlerFunc {
	return func(c *gin.Context) {
		defer func() {
			if err := recover(); err != nil {
				// 记录堆栈信息
				log.Printf("panic: %v\n", err)
				log.Printf("stack: %s\n", debug.Stack())

				// 返回服务器错误
				c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{
					"code": 500,
					"msg":  fmt.Sprintf("系统错误: %v", err),
				})
			}
		}()
		c.Next()
	}
}
